<template>
  <div class="replenishment-list-wrap table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable ref="filterTable" :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #tableBody>
          <a-spin :loading="tableLoading" style="width: 100%" class="table-w">
            <table class="order-table">
              <colgroup>
                <col width="50px" />
                <col :width="showType === 1 ? '100px' : '120px'" />
                <col width="65px" />
                <col :span="24" width="65px" />
                <col width="65px" />
              </colgroup>
              <thead>
                <tr>
                  <th rowspan="3">
                    <p style="width: 40px">序号</p>
                  </th>
                  <th rowspan="3" v-if="showType === 1">
                    <p style="width: 90px">站点</p>
                  </th>
                  <th rowspan="3" v-if="showType === 2">
                    <p style="width: 110px">SKU</p>
                  </th>
                  <th>
                    <p style="width: 55px">美国时间</p>
                  </th>
                  <th v-for="(time, i) in timeListCh" :key="time" :class="{ 'border-r': i === 8 || i === 18 }">T{{ getAreaTime(time, 'ATVPDKIKX0DER') }}</th>
                  <th rowspan="3">
                    <p style="width: 55px">合计数量</p>
                  </th>
                </tr>
                <tr>
                  <th>
                    <p style="width: 55px">中国时间</p>
                  </th>
                  <th v-for="(time, i) in timeListCh" :key="time" :class="{ 'border-r': i === 8 || i === 18 }">{{ time }}</th>
                </tr>
                <tr>
                  <th>
                    <p style="width: 55px">订单时间</p>
                  </th>
                  <th v-for="(time, i) in timeListCh" :key="time" :class="{ 'border-r': i === 8 || i === 18 }">T{{ getAreaTime(time) }}</th>
                </tr>
              </thead>
            </table>
            <a-scrollbar style="height: 100%; overflow: auto">
              <table class="order-table">
                <colgroup>
                  <col width="50px" />
                  <col :width="showType === 1 ? '100px' : '120px'" />
                  <col width="65px" />
                  <col :span="24" width="65px" />
                  <col width="65px" />
                </colgroup>
                <tbody>
                  <tr v-for="(item, i) in tableList" :key="i">
                    <td class="fixed-cell">
                      <p style="width: 40px">{{ i + 1 }}</p>
                    </td>
                    <td v-if="showType === 1" class="fixed-cell">
                      <p style="width: 90px">{{ marketPlaceList[item.marketplace_id]?.name || item.marketplace_id }}</p>
                    </td>
                    <td v-if="showType === 2" class="fixed-cell">
                      <p style="width: 110px">{{ item.sku }}</p>
                    </td>
                    <td class="fixed-cell">
                      <p style="width: 55px"></p>
                    </td>
                    <td v-for="(time, j) in timeListCh" :key="time" :class="{ 'border-r': j === 8 || j === 18 }" :style="`background-color:rgba(255,188,148,${$extract(item.timeMap[time], 'opacity') || 0})`">{{ $extract(item.timeMap[time], 'val') || 0 }}</td>
                    <td class="fixed-cell">
                      <p style="width: 55px">{{ item.total }}</p>
                    </td>
                  </tr>
                </tbody>
              </table>
            </a-scrollbar>
          </a-spin>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="pageSize" :current="pageNum" :page-size-options="[50, 100, 300, 500, 1000]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import TableWrap from '@/components/TableWrap.vue'
  import useBaseDataStore from '@/store/modules/base-data'
  import { getMarketplaceGroupOrder, getSellerIdGroupOrder } from '@/api/advert'
  import { marketPlaceList, MarketTimeZone } from '@/utils/globalData'
  import dayjs from 'dayjs'

  onMounted(async () => {
    getTableList()
    getMarketList()
    getShopList()
  })

  const timeListCh = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']

  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'marketplace_id',
      label: '站点',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'shopId',
      label: '全部店铺',
      value: ref(),
      type: 'select',
      width: 200,
      optionItems: [],
      attrs: {
        isCorrelation: true,
        correlationKey: 'marketplaceId',
      },
    },
    {
      type: 'input_keyword',

      key: 'sku_list',
      keyItems: [{ label: 'SKU', value: 'sku_list' }],
      keyWidth: '70',
      value: ref(),
      placeholder: 'SKU',
      label: 'SKU',
      width: 180,
      isMultiple: true,
    },
    {
      type: 'keyword_date_range',
      key: 'outStockDate',
      keyItems: [{ label: '出单时间', value: 'outStockDate' }],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        mode: 'week',

        dayStartOfWeek: 1,
      },
    },
  ])

  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const showType = ref(1)
  const currentMarkedtId = ref()

  const filterData = ref<any>({})
  const useBaseData = useBaseDataStore()
  const filterTable = ref()
  const total = ref(0)
  const pageSize = ref(300)
  const pageNum = ref(1)
  let allList: Array<any> = []

  // 分页
  function changePage(val: number) {
    pageNum.value = val
    getListByPage()
  }
  function sizeChange(val: number) {
    pageSize.value = val
    pageNum.value = 1
    getListByPage()
  }
  // 获取时间差
  function getAreaTime(time: any, markedtId?: string) {
    let marketplaceId = markedtId || currentMarkedtId.value
    let diff = MarketTimeZone[marketplaceId]
    if (!marketplaceId || diff === undefined) return '--'
    let val = time * 1 + diff
    if (val < 0) return 24 + val
    if (val >= 24) return val - 24
    return val
  }

  // 获取站点
  async function getMarketList() {
    await useBaseData.getMarketList()
    filterItem.value[0].optionItems = useBaseData.markedtList.map((el: any) => {
      return {
        label: el.marketplaceName,
        value: el.marketplaceId,
      }
    })
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    filterItem.value[1].optionItems = useBaseData.shopList.map((el: any) => {
      return {
        label: el.shopName,
        value: el.sellerMarketId,
      }
    })
  }
  // 条件查询
  function searchByVal(info: any) {
    pageNum.value = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 获取列表
  async function getTableList() {
    tableList.value = []
    // 店铺和sku未选择查询店铺信息
    if (!filterData.value.shopId && !filterData.value.sku_list) {
      showType.value = 1
      getMarketplaceList()
    } else {
      showType.value = 2
      getSkuList()
    }
  }
  // 按站点汇总
  async function getMarketplaceList() {
    tableLoading.value = true
    let params: any = {
      marketplace_id: filterData.value.marketplace_id,
    }
    if (filterData.value.startDate) {
      params.begin_wk = dayjs(filterData.value.startDate).format('ggggww')
      params.end_wk = dayjs(filterData.value.endDate).format('ggggww')
    }
    currentMarkedtId.value = params.marketplace_id
    const res: any = await getMarketplaceGroupOrder({ param: params })
    let list = res?.data?.rs?.result || []
    tableLoading.value = false
    let listMap: any = {}
    list.forEach((el: any) => {
      if (!listMap[el.marketplace_id]) {
        listMap[el.marketplace_id] = {
          marketplace_id: el.marketplace_id,
          timeMap: {},
          total: 0,
        }
      }
      if (!listMap[el.marketplace_id].timeMap[el.beijin_hour]) {
        listMap[el.marketplace_id].timeMap[el.beijin_hour] = {}
      }
      listMap[el.marketplace_id].timeMap[el.beijin_hour].val = el.item_cnt
      listMap[el.marketplace_id].timeMap[el.beijin_hour].hour = el.beijin_hour

      listMap[el.marketplace_id].total += el.item_cnt
    })
    setTdOpacity(Object.values(listMap))
  }
  // 按sku汇总
  async function getSkuList() {
    tableLoading.value = true
    let shopId = filterData.value.shopId?.split('_')
    let params: any = {
      seller_id: shopId?.[0],
      marketplace_id: shopId?.[1] || filterData.value.marketplace_id,
      sku_list: filterData.value.sku_list ? filterData.value.sku_list?.split(',') : null,
    }
    if (filterData.value.startDate) {
      params.begin_wk = dayjs(filterData.value.startDate).format('ggggww')
      params.end_wk = dayjs(filterData.value.endDate).format('ggggww')
    }
    currentMarkedtId.value = params.marketplace_id
    const res: any = await getSellerIdGroupOrder({ param: params })
    let list = res?.data?.rs?.result || []
    tableLoading.value = false

    let listMap: any = {}
    list.forEach((el: any) => {
      if (!listMap[el.sku]) {
        listMap[el.sku] = {
          sku: el.sku,
          timeMap: {},
          total: 0,
        }
      }
      if (!listMap[el.sku].timeMap[el.beijin_hour]) {
        listMap[el.sku].timeMap[el.beijin_hour] = {}
      }
      listMap[el.sku].timeMap[el.beijin_hour].val = el.item_cnt
      listMap[el.sku].timeMap[el.beijin_hour].hour = el.beijin_hour
      listMap[el.sku].total += el.item_cnt || 0
    })
    setTdOpacity(Object.values(listMap))
  }
  // 设置背景色
  function setTdOpacity(list: Array<any>) {
    list.forEach((el: any) => {
      let timeList = timeListCh.map((time: any) => {
        return { time: time, val: el.timeMap[time]?.val || 0 }
      })
      timeList = timeList.sort((a, b) => {
        return a.val - b.val
      })
      Object.keys(el.timeMap).forEach((time: any) => {
        let timeVal = el.timeMap[time]
        timeVal.sort = timeList.findIndex((row: any) => row.time == time) + 1
        timeVal.opacity = timeVal.sort / 24
      })
    })
    list = list.sort((a, b) => {
      return b.total - a.total
    })
    allList = list
    total.value = list.length
    getListByPage()
    // tableList.value = JSON.parse(JSON.stringify(allList))
  }
  function getListByPage() {
    tableList.value = []
    tableList.value = allList.slice((pageNum.value - 1) * pageSize.value, pageNum.value * pageSize.value)
  }
</script>
<style lang="less" scoped>
  .table-w {
    border-top: 1px solid var(--color-neutral-3);
    border-left: 1px solid var(--color-neutral-3);
    height: 100%;
    overflow: hidden;
    .arco-scrollbar {
      height: calc(100% - 81px);
    }
  }
  .order-table {
    font-size: 12px;
    word-break: break-all;
    table-layout: fixed;
    thead {
      background-color: var(--color-neutral-2);
      th {
        border-right: 1px solid var(--color-neutral-3);
        border-bottom: 1px solid var(--color-neutral-3);
        padding: 4px 5px;
        text-align: left;
      }
    }
    td {
      border-right: 1px solid var(--color-neutral-3);
      border-bottom: 1px solid var(--color-neutral-3);
      padding: 4px 5px;
      height: 40px;
      &.fixed-cell {
        background-color: var(--color-neutral-2);
      }
    }
    .border-r {
      border-right: 2px solid var(--color-neutral-5);
    }
  }
</style>
